package com.lwl.blue.commont.utils;

import com.aliyun.openservices.shade.org.apache.commons.lang3.ArrayUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils {

    /**
     * 默认的文件名最大长度 100
     */
    private static final int DEFAULT_FILE_NAME_LENGTH = 100;
    private static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
    private static final String[] FLASH_EXTENSION = {"swf", "flv"};
    private static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
            "asf", "rm", "rmvb"};
    private static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // pdf
            "pdf",
            // xml
            "xml"};

    /**
     * 根据文件路径上传
     *
     * @param fileSavePath 文件保存路径
     * @param file         上传的文件
     * @throws IOException
     */
    public static void upload(String fileSavePath, MultipartFile file) throws IOException {
        upload(fileSavePath, file, DEFAULT_ALLOWED_EXTENSION);
    }

    /**
     * 文件上传
     *
     * @param fileSavePath
     * @param file
     * @param allowedExtensions
     * @throws IOException
     */
    public static void upload(String fileSavePath, MultipartFile file, String[] allowedExtensions) throws IOException {

        //检查文件名称长度
//        if (file.getOriginalFilename().length() > DEFAULT_FILE_NAME_LENGTH) {
//            throw new BusinessException("error.file.name.length.incorrect", "" + DEFAULT_FILE_NAME_LENGTH);
//        }

        //检查文件扩展名
        String extension = getExtension(file);
        if (ObjectUtils.isEmpty(extension) || !ArrayUtils.contains(allowedExtensions, extension.toLowerCase())) {
//            throw new BusinessException("error.file.extension.incorrect");
        }

        //保存文件
        File save = new File(fileSavePath);
        org.apache.commons.io.FileUtils.forceMkdir(save.getParentFile());
        file.transferTo(save);
    }

    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, double size, String unit) {
        Double fileSize = new Double(0);
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (1 == fileSize.compareTo(size)) {
            return false;
        }
        return true;
    }

    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (ObjectUtils.isEmpty(extension)) {
            switch (file.getContentType()) {
                case "image/png":
                    return "png";
                case "image/jpg":
                    return "jpg";
                case "image/jpeg":
                    return "jpeg";
                case "image/bmp":
                    return "bmp";
                case "image/gif":
                    return "gif";
                default:
                    return "";
            }
        }
        return extension;
    }

    /**
     * 下载文件 - 返回下载后的文件存储路径
     *
     * @param url      文件地址
     * @param dir      存储目录
     * @param fileName 存储文件名
     */
    public static void downloadHttpUrl(String url, String dir, String fileName) {
        try {
            URL httpUrl = new URL(url);
            File dirFile = new File(dir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            org.apache.commons.io.FileUtils.copyURLToFile(httpUrl, new File(dir + fileName));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从网络url中下载文件
     *
     * @param urlStr   路径
     * @param fileName 文件名称
     * @param savePath 存储路径
     * @return
     */
    public static String downloadFromUrl(String urlStr, String fileName, String savePath) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 得到输入流
            InputStream inputStream = conn.getInputStream();
            // 获取自己数组
            byte[] getData = readInputStream(inputStream);

            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            // System.out.println("info:"+url+" download success");
            return saveDir + File.separator + fileName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 下载文件方式1
     *
     * @param response HttpServletResponse对象
     * @param downFile 服务器文件路径
     */
    public static void downloadFile(HttpServletResponse response, String downFile) {
        byte[] buff = new byte[1024];

        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            bis = new BufferedInputStream(new FileInputStream(new File(downFile)));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param filePath  服务器文件完整路径
     * @param fileName  文件名称
     * @param userAgent 浏览器信息
     * @return 对象
     * @throws IOException
     */
    public static ResponseEntity<byte[]> downloadFile2(String filePath, String fileName, String userAgent) throws IOException {
        // 构建File
        File file = new File(filePath);
        // ok表示http请求中状态码200
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
        // 内容长度
        builder.contentLength(file.length());
        // application/octet-stream 二进制数据流（最常见的文件下载）
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用URLEncoding.decode对文件名进行解码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        // 根据浏览器类型，决定处理方式
        if (userAgent.indexOf("MSIE") > 0) {
            builder.header("Content-Disposition", "attachment; filename=" + fileName);
        } else {
            builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + fileName);
        }
        return builder.body(org.apache.commons.io.FileUtils.readFileToByteArray(file));
    }

    public static void createDirOrFile(String filePath, String fileType) throws IOException {
        File file = new File(filePath);
        if (fileType.equals("folder")) {
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            if (!file.exists()) {
                file.createNewFile();
            }
        }

    }

}
